﻿using System;
using System.Net;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace G.SL.Net.Oauth
{
    public class Oauth2Valid
    {
        /// <summary>
        /// 刷新AccessToken
        /// </summary>
        /// <returns></returns>
        public static void RefreshToken(string projectName, Action<OAuth2AccessToken> callBack)
        {
            OAuth2AccessToken.Clear("OAuth2AccessToken" + projectName);
            Valid(projectName, callBack);
            //OAuth2AccessToken.Load();
            //if (OAuth2AccessToken.CurrentToken == null)
            //{
            //    throw new Exception("无法获取OAuth2AccessToken，请重新登陆");
            //}
            //string refreshTokenUrl = string.Format("{0}?client_id={1}&client_secret={2}&grant_type=refresh_token&refresh_token={3}", Oauth2Config.Token_Authorize_Url, Oauth2Config.ClientID, Oauth2Config.ClientSecret, OAuth2AccessToken.CurrentToken.RefreshToken);
            //HttpGet get = new HttpGet(refreshTokenUrl);
            //var result = await get.RequestAsync();
            //if (result.Exception == null)
            //{
            //    OAuth2AccessToken token = G.Utils.SerializerHelp.JsonDeserialize<OAuth2AccessToken>(result.Result);
            //    token.Save(result.Result);
            //}
            //else
            //    throw new Exception("获取token失败");
        }


        /// <summary>
        /// 验证oauth2.0权限，获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static void Valid(string projectName, Action<OAuth2AccessToken> callBack)
        {
            var t = OAuth2AccessToken.Load("OAuth2AccessToken" + projectName);
            if (t != null)
            {
                callBack(t);
                return;
            }
            ChildWindow c = new ChildWindow();
            WebBrowser web = new WebBrowser() { Height = 500, Width = 700 };
            c.Content = web;
            string authorize_url = string.Format("{0}?client_id={1}&response_type={2}&redirect_uri={3}&scope=read,write", Oauth2Config.Request_Authorize_Url, Oauth2Config.ClientID, Oauth2Config.Authorize_ResponseType, System.Windows.Browser.HttpUtility.UrlEncode(Oauth2Config.RedirectUri));
            web.Navigate(new Uri(authorize_url));
            c.Show();


            web.LoadCompleted += (s, e) =>
            {
                if (e.Uri.OriginalString.StartsWith(Oauth2Config.RedirectUri))
                {
                    string code = e.Uri.Query;
                    string pa = "code=(.+?)$";
                    var match = Regex.Match(code, pa, RegexOptions.IgnoreCase);
                    if (!match.Success)
                        throw new Exception("检索code失败！");
                    code = match.Groups[1].Value;
                    c.Close();
                    HttpPost get = new HttpPost(string.Format("{0}?client_id={1}&client_secret={2}&grant_type={3}&redirect_uri={4}&code={5}", Oauth2Config.Token_Authorize_Url, Oauth2Config.ClientID, Oauth2Config.ClientSecret, "authorization_code", Oauth2Config.RedirectUri, code));
                    get.Request((staus, str) =>
                    {
                        if (staus == null)
                        {
                            OAuth2AccessToken token = Utils.SerializerHelp.JsonDeserialize<OAuth2AccessToken>(str);
                            token.Save("OAuth2AccessToken" + projectName, str);
                            callBack(token);
                        }
                        else
                            throw new Exception("获取token失败");
                    });
                }
            };
        }



    }

    [DataContract]
    public class OAuth2AccessToken
    {
        internal static OAuth2AccessToken Load(string key)
        {
            //var settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            //if (settings.Contains(key))
            //{
            //    var token = Utils.SerializerHelp.JsonDeserialize<OAuth2AccessToken>(settings[key] as string);
            //    CurrentToken = token;
            //    return token;
            //}
            return null;
        }

        internal static void Clear(string key)
        {
            var settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains(key))
            {
                settings.Remove(key);
                settings.Save();
            }
        }

        public static OAuth2AccessToken CurrentToken { get; internal set; }
        public OAuth2AccessToken()
        {
            CurrentToken = this;
        }

        [DataMember(Name = "access_token")]
        public string AccessToken { get; set; }

        [DataMember(Name = "expires_in")]
        public string ExpiresIn { get; set; }

        [DataMember(Name = "refresh_token")]
        public string RefreshToken { get; set; }

        [DataMember(Name = "token_type")]
        public string TokenType { get; set; }

        [DataMember(Name = "uid")]
        public string Uid { get; set; }

        [DataMember(Name = "scope")]
        public string Scope { get; set; }

        internal void Save(string key, string jsonStr)
        {
            var settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            settings[key] = jsonStr;
            settings.Save();
            CurrentToken = this;
        }
    }
}
